package cn.sh.library.mgts.sparql.impl;

import java.io.ByteArrayOutputStream;

import org.apache.jena.query.ARQ;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.riot.RDFDataMgr;
import org.apache.jena.riot.RDFFormat;
import org.apache.jena.riot.writer.JsonLDWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.github.jsonldjava.core.JsonLdOptions;

import cn.sh.library.mgts.common.Constant;
import cn.sh.library.mgts.framework.exception.CustomRuntimeException;
import cn.sh.library.mgts.sparql.ConstructSparql;
import cn.sh.library.mgts.sparql.SparqlExecution;
import cn.sh.library.mgts.utils.StringUtilC;
@Service
public class ConstructSparqlImpl implements ConstructSparql{

//	private static Logger loggerBulk = LoggerFactory.getLogger(Constant.LOGGER_BULK_NAME);

	@Override
	public String construnct(String endpoint, String sparql) {
		Model model = null;
		ARQ.getContext().set(JsonLDWriter.JSONLD_CONTEXT, Constant.CONSTRUCT_CONTEXT);
		model = SparqlExecution.construct(endpoint, sparql);
		// 发生异常情况下，将uri输出到log文件
		if (model.getGraph().size() <= 0) {
			throw new CustomRuntimeException();
		}

		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		RDFDataMgr.write(stream, model, RDFFormat.JSONLD_FLAT);
		
		return StringUtilC.StreamToString(stream);
	}
	

	@Override
	public String construnct(String endpoint, String sparql, String frame) {
		Model model = null;
		JsonLdOptions options = new JsonLdOptions();
		options.setProcessingMode(JsonLdOptions.JSON_LD_1_1);
		options.setOmitDefault(true);
		ARQ.getContext().set(JsonLDWriter.JSONLD_OPTIONS, options);
		// 框架结构
		ARQ.getContext().set(JsonLDWriter.JSONLD_FRAME, frame);

		model = SparqlExecution.construct(endpoint, sparql);
		// 发生异常情况下，将uri输出到log文件
		if (model.getGraph().size() <= 0) {
			System.out.println(sparql);

			throw new CustomRuntimeException();
		}

		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		RDFDataMgr.write(stream, model, RDFFormat.JSONLD_FRAME_FLAT);
		
		return StringUtilC.StreamToString(stream);
	}
}
